package com.sunday.aomicaichang.ui;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.squareup.picasso.Picasso;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.MD5Utils;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.aomicaichang.R;
import com.sunday.aomicaichang.adpter.MenuDetailAdapter;
import com.sunday.aomicaichang.adpter.MenuDetailCookAdapter;
import com.sunday.aomicaichang.constValues.ConstValue;
import com.sunday.aomicaichang.http.ApiClient;
import com.sunday.aomicaichang.model.MenuDetail;
import com.sunday.member.http.MemberClient;
import com.sunday.member.utils.SignUtil;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by yun_sheng on 2017/6/7.
 */

public class MenuDetailActivity extends BaseActivity {
    @Bind(R.id.img)
    ImageView img;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.sub)
    TextView sub;
    @Bind(R.id.btn_collect)
    RelativeLayout btnCollect;
    @Bind(R.id.time)
    TextView time;
    @Bind(R.id.difficulty)
    TextView difficulty;
    @Bind(R.id.health)
    TextView health;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.nested_scroll_webview1)
    WebView webView;
    @Bind(R.id.tv_collect)
    TextView tvCollect;
    @Bind(R.id.tv_collect1)
    TextView tvCollect1;
    @Bind(R.id.btn_collect1)
    RelativeLayout btnCollect1;
    @Bind(R.id.btn)
    TextView btn;
    @Bind(R.id.num)
    TextView num;
    @Bind(R.id.order)
    TextView order;
    @Bind(R.id.recycler_view1)
    RecyclerView recyclerView1;
    @Bind(R.id.ly)
    RelativeLayout ly;
    @Bind(R.id.back)
    ImageView back;
    private long id;
    private MenuDetail menuDetail;
    private MenuDetailAdapter adapter;
    private MenuDetailCookAdapter adapter1;
    private LinearLayoutManager layoutManager, layoutManager1;
    private List<MenuDetail.ProductsBean> productsBeanList = new ArrayList<>();
    private List<MenuDetail.CookBooksBean> cookBooksBeanList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_detail);
        ButterKnife.bind(this);
        id = getIntent().getLongExtra("id", 0);
        layoutManager = new LinearLayoutManager(mContext);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new MenuDetailAdapter(mContext);
        recyclerView.setAdapter(adapter);
        layoutManager1 = new LinearLayoutManager(mContext);
        layoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView1.setLayoutManager(layoutManager1);
        recyclerView1.setItemAnimator(new DefaultItemAnimator());
        adapter1 = new MenuDetailCookAdapter(mContext);
        recyclerView1.setAdapter(adapter1);
        getData();
//        rightMenu.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (menuDetail.getShareUrl() == null || menuDetail.getShareTitle() == null) {
//                    ToastUtils.showToast(mContext, "数据不完整");
//                    return;
//                }
//                ShareWindow shareWindow = new ShareWindow(mContext, menuDetail.getShareUrl(), menuDetail.getShareTitle(), menuDetail.getShareImage(), productDetail.getShareDesc());
//                shareWindow.showPopupWindow(rightMenu);
//            }
//        });
    }

    private void getData() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"id", "nonce"};
        String[] str2 = new String[]{String.valueOf(id), nonce};
        showLoadingDialog(0);
        Call<ResultDO<MenuDetail>> call = ApiClient.getApiAdapter().findOne(id, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO<MenuDetail>>() {
            @Override
            public void onResponse(Call<ResultDO<MenuDetail>> call, Response<ResultDO<MenuDetail>> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    menuDetail = response.body().getResult();
                    updateView();

                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<MenuDetail>> call, Throwable t) {
                dissMissDialog();
            }
        });
    }

    private void updateView() {
        if (menuDetail.getImage() != null) {
            Picasso.with(mContext)
                    .load(menuDetail.getImage())
                    .error(R.mipmap.ic_product)
                    .into(img);
        }
        tvName.setText(menuDetail.getName());
        sub.setText(menuDetail.getViceName());
        time.setText("时间：" + menuDetail.getTime());
        difficulty.setText("难度：" + menuDetail.getDifficulty());
        health.setText(menuDetail.getDetail());
        if (menuDetail.getCookBooks().size() != 0) {
            ly.setVisibility(View.VISIBLE);
            num.setText(menuDetail.getCookBooks().size() + "个作品");
        } else {
            ly.setVisibility(View.GONE);
        }
        if (menuDetail.getIsCollection() == 0) {
            btnCollect.setVisibility(View.VISIBLE);
            btnCollect1.setVisibility(View.GONE);
        } else {
            btnCollect.setVisibility(View.GONE);
            btnCollect1.setVisibility(View.VISIBLE);
        }
        if (productsBeanList != null)
            productsBeanList.clear();
        productsBeanList.addAll(menuDetail.getProducts());
        adapter.setmData(productsBeanList);
        adapter.notifyDataSetChanged();
        cookBooksBeanList.addAll(menuDetail.getCookBooks());
        adapter1.setmData(cookBooksBeanList);
        adapter1.notifyDataSetChanged();
        //启用支持javascript
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setBuiltInZoomControls(false);
        settings.setSupportZoom(false);
        settings.setDomStorageEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url)) {
                    view.loadUrl(url);
                } else {
                    dissMissDialog();
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dissMissDialog();
            }
        });
        if (menuDetail.getProducts().size() == 0 || menuDetail.getProducts() == null) {
            btn.setVisibility(View.GONE);
            order.setVisibility(View.GONE);
        } else {
            btn.setVisibility(View.VISIBLE);
            order.setVisibility(View.VISIBLE);
        }
        webView.loadUrl(menuDetail.getDescUrl());
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCart();
            }
        });
        btnCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect();
            }
        });
        btnCollect1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collect();
            }
        });
    }

    private void addCart() {
        List<String> cartIds = new ArrayList<>();
        for (MenuDetail.ProductsBean item : productsBeanList) {
            cartIds.add(String.valueOf(item.getId()));
        }
        List<String> nums = new ArrayList<>();
        for (MenuDetail.ProductsBean item : productsBeanList) {
            nums.add(String.valueOf(item.getNum()));
        }
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"productIds", "villageId", "nums", "nonce"};
        Integer villageId = SharePerferenceUtils.getIns(mContext).getInt(ConstValue.AREA, 0);
        String[] str2 = new String[]{StringUtils.listToString(cartIds), String.valueOf(villageId), StringUtils.listToString(nums), nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = MemberClient.getApiAdapter().addCart(villageId, StringUtils.listToString(cartIds),
                StringUtils.listToString(nums), nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                dissMissDialog();
                if (isFinish ||response.body() == null) {
                    return;
                }
                if (response.body().getCode() == 0) {
                    Toasty.success(mContext, "成功加入购物车").show();
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage() + "");
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                Toasty.error(mContext, "网络连接错误").show();
            }
        });
    }

    private void collect() {
        String nonce = MD5Utils.random();
        String[] str1 = new String[]{"type", "otherId", "nonce"};
        String[] str2 = new String[]{String.valueOf(2), String.valueOf(id), nonce};
        showLoadingDialog(0);
        Call<ResultDO> call = ApiClient.getApiAdapter().save(2, id, nonce, SignUtil.getSign(str1, str2));
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish || response.body() == null) {
                    return;
                }
                dissMissDialog();
                if (response.body().getCode() == 0) {
                    if (response.body().getResult() == null) {
                        return;
                    }
                    if (menuDetail.getIsCollection() == 0) {
                        ToastUtils.showToast(mContext, "已收藏");
                        getData();
                    } else {
                        ToastUtils.showToast(mContext, "已取消收藏");
                        getData();
                    }
                } else {
                    ToastUtils.showToast(mContext, response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                dissMissDialog();
            }
        });
    }
}
